# file: format_table_2.R
# Description: Creates summary table reporting full set of different regression results. 
# Reported in Table 2 in the paper: Summary of Regressions of Turnout on Partisan Alignment

rm(list=ls())

#install.packages(c("data.table","xtable"))

require(data.table)
require(xtable)

setwd("~/Desktop/replication")

load("estimates.RData")


out.hyp <- c()
for (item in unique(estimates$file)){
	
	temp <- estimates[file==item]

	hyp2.rd <- as.logical(temp[3,estimate] - temp[4,estimate] >= 0)
	hyp2.sig5 <- abs((temp[3,estimate] - temp[4,estimate])/sqrt(temp[3,se]^2 + temp[4,se]^2 ))>=1.96 & hyp2.rd
	hyp2.sig10 <- abs((temp[3,estimate] - temp[4,estimate])/sqrt(temp[3,se]^2 + temp[4,se]^2 ))>=1.645 & hyp2.rd
	
	out.hyp <- rbind(out.hyp,data.table(temp[1,.(file,coef)],right.direction=hyp2.rd,sig5=hyp2.sig5,sig10=hyp2.sig10))
}


estimates[coef=="Partisan Aligned" ,right.direction:=estimate>0]
estimates[coef=="Partisan Misaligned",right.direction:=estimate<0]



estimates[,n:=1:.N]

estimates <- rbind(estimates[!(n%%3==0 | n%%4==0)],out.hyp,fill=T)
estimates[,n:=NULL]

estimates[grepl("all",file),years:="All Years"]; estimates[grepl("mid",file),years:="Mid-Term"]; estimates[grepl("prs",file),years:="Pres."]
estimates[grepl("bfe",file),spec:="BFE"]; estimates[is.na(spec),spec:="DID"]


estimates_supplement[coef=="Partisan Aligned",right.direction:=estimate>0]
estimates_supplement[coef=="Partisan Misaligned",right.direction:=estimate<0]


estimates_supplement[grepl("all",file),years:="All Years"]; estimates_supplement[grepl("mid",file),years:="Mid-Term"]; estimates_supplement[grepl("prs",file),years:="Pres."]
estimates_supplement[grepl("bfe",file),spec:="BFE"]; estimates_supplement[is.na(spec),spec:="DID"]


estimates_final <- rbind(estimates[!is.na(years)],estimates_supplement)

#combine rows 1 and 2 for each file w/ combined test for 3 and 4

out<-estimates_final[,.("\\shortstack{Right \\\\ Direction}"=paste(sum(right.direction),"/",.N,sep=""),"\\shortstack{Right Direction \\& \\\\ Sig. at p=0.05}"=paste(sum(right.direction==T & sig5==T),"/",.N,sep=""),"\\shortstack{Right Direction \\& \\\\ Sig. at p=0.10}"=paste(sum(right.direction==T & sig10==T),"/",.N,sep="")),by=.("Years"=years,"Specification"=spec)]
setkey(out,Years,Specification)

print(xtable(out, align="lllccc",label="regsum",
caption="Summary of Regressions of Turnout on Partisan Alignment"), include.colnames=T, include.rownames=F,caption.placement = "top",
sanitize.text.function = identity, file="out/tab2.tex",floating = TRUE) 

